﻿using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
using System.Collections.Generic;

public class WithinSight : Conditional
{
	public float fieldOfViewAngle;
	public string targetTag;
	public SharedTransform target;
	
	private List<Transform> possibleTargets = new List<Transform>();

	public override void OnAwake()
	{
		
	}
	
	public override void OnStart()
	{
		var targets = GameObject.FindGameObjectsWithTag(targetTag);
		
		for (int i = 0; i < targets.Length; ++i) {
			if (targets[i].transform.gameObject.activeSelf)
				possibleTargets.Add(targets[i].transform);
		}
	}
	
	public override void OnEnd()
	{
		possibleTargets.Clear();
	}

	public override TaskStatus OnUpdate()
	{
		for (int i = 0; i < possibleTargets.Count; ++i) {
			if (withinSight(possibleTargets[i], fieldOfViewAngle)) {
				target.Value = possibleTargets[i];
				return TaskStatus.Success;
			}
		}
		return TaskStatus.Failure;
	}

	public bool withinSight(Transform targetTransform, float fieldOfViewAngle)
	{
		if (targetTransform==null)
			return false;

		Vector3 direction = targetTransform.position - transform.position;
		return Vector3.Angle(direction, transform.forward) < fieldOfViewAngle;
	}
}